<template>
    <el-drawer 
        title="使用店铺" :visible.sync="visible" direction="rtl"
        size="100%" :before-close="handleClose" class="store-drawer" ref="storeDrawer">
        <div class="search-list">
            <el-table 
                border :data="dataList" row-key="store_id" ref="tableRef"
                :default-sort="{ prop: 'store_id' }" @selection-change="handleSelectionChange">
                <el-table-column 
                    type="selection" width="60" align="center" reserve-selection>
                </el-table-column>
                <el-table-column 
                    prop="store_name" label="店铺名称" min-width="190" align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column 
                    prop="member_name" label="店主用户名" min-width="190" align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column 
                    prop="grade_id" label="所属等级" min-width="140" align="center" 
                    :formatter="(row, column, cellValue) => handleLevel(cellValue)">
                </el-table-column>
                <el-table-column 
                    label="问卷链接" min-width="170" align="center" #default="{ row }">
                    <!-- <el-button type="text" @click="handleCopy(row.apply_id)">
                        点击复制
                    </el-button> -->
                    <el-button type="text" @click="handleWxsQrocde(row.apply_id)">
                        小程序码
                    </el-button>
                </el-table-column>
                <el-table-column label="状态" min-width="100" align="center" #default="{ row }">
                    <el-switch
                        v-model="row.status" v-if="data.status == 1 && [1, 3].includes(+row.status)"
                        active-value="1" inactive-value="3" @change="handleStore('update', [ row.store_id ], row)">
                    </el-switch>
                    <span :class="`status-${row.status}`" v-else>{{ row.status_desc }}</span>
                </el-table-column>
            </el-table>
        </div>
        <div class="bottom flex-item">
            <div class="btn-group">
                <template v-if="data.status < 2">
                    <el-button type="primary" @click="handleStore('add')">添加店铺</el-button>
                    <el-button type="primary" @click="handleStore('del')">删除店铺</el-button>
                </template>
            </div>
            <div class="paginationOne">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageArr.page"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pageArr.pageSize"
                    :total="pageArr.total"
                    layout="total, sizes, prev, pager, next, jumper">
                </el-pagination>
            </div>
        </div>
        <span 
            ref="copyRef" class="wxs-link-url" @click="copyUrl" :data-clipboard-text="wxsLinkUrl">
        </span>
        <store-list 
            :showStoreBox.sync="dialogOptions.visible" 
            @chooseStore="updateStoreInfo" :chooseAll="true" :row-click="false">
        </store-list>
    </el-drawer>
</template>
<script>
import Clipboard from "clipboard"
import storeList from "@/components/home/store-list.vue"
import { Loading } from 'element-ui'
export default {
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        data: {
            type: Object,
            default: () => ({})
        }
    },
    components: { storeList },
    data() {
        return {
            selectTime: '',    // 时间 [start, end]
            dataList: [],      // 列表数据
            selectedList: [],  // 已选中的数据
            dialogOptions: {
                visible: false
            },
            wxsLinkUrl: '',    // 问卷小程序链接
            pageArr: {    
                page: 1,       // 当前页码
                pageSize: +localStorage.getItem('pageSize') || 20,
                total: 0       // 数据总数
            }
        }
    },
    computed: {
        getActionType() {
            return actionType()
        }
    },
    watch: {
        visible: {
            immediate: true,
            handler(val) {
                if (val) {
                    // $nextTick() 里执行请求，解决loading动画被el-drawer遮挡偶现的问题
                    this.$nextTick(() => this.getData())
                }
            }
        }
    },
    methods: {
        async getData() {
            try {
                const params = {
                    pageSize: this.pageArr.pageSize,
                    page: this.pageArr.page,
                    questionnaire_id: this.data.questionnaire_id
                }
                const res = await this.$http.get(
                    '/admin/yt_car/index.php?act=questionnaire&op=questionnaireApplyList', 
                    { params }
                )
                if (res.code == 1) {
                    this.dataList = res.data?.list || []
                    this.pageArr.total = +res.data.totalCount
                }
            } catch (error) {
                error && this.$message.error(`${error}`)
            }
        },
        handleClose() {
            this.handleClearSelection()
            this.dataList = []
            this.pageArr.total = 0
            this.pageArr.page = 1
            this.$emit("update:visible", false)
        },
        handleSizeChange(pageSize) {
            localStorage.setItem('pageSize', pageSize)
            this.pageArr.pageSize = pageSize
            this.pageArr.page = 1
            this.getData()
        },
        handleCurrentChange(page) {
            this.pageArr.page = page
            this.getData()
        },
        handleCopy(apply_id) {
            const params = { apply_id }
            this.$http.get("/admin/yt_car/index.php?act=questionnaire&op=getQuestionnaireUrlLink", { params })
            .then(res => {
                if (res.code == 1) {
                    this.wxsLinkUrl = res.data.link
                    this.$nextTick(() => this.$refs['copyRef'].click())
                } else {
                    throw res.msg
                }
            }).catch(error => {
                error && this.$message.error(`${error}`)
            })
        },
        copyUrl() {
            const clipboard = new Clipboard('.wxs-link-url')
            clipboard.on('success', () => {
                this.$message.success('复制成功')
                clipboard.destroy()
            })
            clipboard.on('error', () => {
                this.$message.error('复制失败')
                clipboard.destroy()
            })
        },
        handleWxsQrocde(apply_id) {
            const { origin } = this.$store.state.location
            const img = new Image()
            img.src = `${origin}/admin/yt_car/index.php?act=questionnaire&op=getQuestionnaireQrCode&apply_id=${apply_id}`
            this.$msgbox({
                title: `小程序码`,
                message: <img src={ img.src } />,
                customClass: 'qrcode-view',
                showConfirmButton: false
            }).catch(() => {})
            setTimeout(() => {
                const loading = Loading.service({
		        	lock: false,
		        	background: 'rgba(0, 0, 0, 0)'
		        })
                img.onload = () => loading.close()
                img.onerror = () => {
                    this.$message.error('小程序码加载失败')
                    loading.close()
                }
            }, 10)
        },
        handleSelectionChange(val) {
            this.selectedList = [ ...val ]
        },
        handleClearSelection() {
            this.selectedList = []
            this.$refs.tableRef.clearSelection()
        },
        async handleStore(type = 'update', store_ids = '', row = {}) {
            try {
                const { questionnaire_id } = this.data
                switch (type) {
                    case 'del':
                        if (this.selectedList.length <= 0) {
                            return this.$message.error('请先选中数据')
                        }
                        await this.$alert(`确定删除已选中的店铺？`, "温馨提示", {
                            type: 'warning',
                            showCancelButton: true
                        })
                        const apply_ids = this.getStoreIds(this.selectedList, 'apply_id')
                        let res = await this.$http.post(
                            '/admin/yt_car/index.php?act=questionnaire&op=delQuestionnaireApply', 
                            { questionnaire_id, apply_ids }
                        )
                        if (res.code == 1) {
                            this.handleClearSelection()
                            this.getData()
                            return this.$message.success('删除成功')
                        }
                        throw res.msg
                    case 'add':
                        this.dialogOptions = { visible: true }
                        break
                    case 'insert':
                        res = await this.$http.post(
                            '/admin/yt_car/index.php?act=questionnaire&op=addQuestionnaireApply', 
                            { questionnaire_id, store_ids }
                        )
                        if (res.code == 1) {
                            this.getData()
                            return this.$message.success('添加成功')
                        }
                        throw res.msg
                    case 'update':
                        // 执行el-switch change后status的状态值已经改变
                        const oldStatus = row.status == 1 ? 3 : 1
                        const status = row.status == 3 ? 2 : 1
                        let successMsg = '启用成功'
                        if (status == 2) {
                            await this.$alert(`确定停用当前店铺？`, "温馨提示", {
                                type: 'warning',
                                showCancelButton: true
                            }).catch(() => {
                                row.status = `${ oldStatus }` // 恢复为之前的状态
                                return Promise.reject('cancel')
                            })
                            successMsg = '停用成功'
                        }
                        res = await this.$http.post(
                            '/admin/yt_car/index.php?act=questionnaire&op=switchApplyStatus', 
                            { apply_id: row.apply_id, type: status }
                        )
                        if (res.code == 1) {
                            return this.$message.success(successMsg)
                        } else {
                            row.status = `${ oldStatus }`
                        }
                        throw res.msg
                    default:
                }
            } catch (error) {
                error && error != 'cancel' && this.$message.error(`${error}`)
            }
        },
        getStoreIds(data, key = 'storeId') {
            const store_ids = [ ...new Set(data.map(item => item[key])) ]
            return store_ids.join(',')
        },
        updateStoreInfo(val) {
            if (Object.prototype.toString.call(val) === '[object Object]') {
                val = [ val ]
            }
            if (val?.length <= 0) return
            const store_ids = this.getStoreIds(val)
            this.handleStore('insert', store_ids)
        },
        handleLevel(val) {
            switch (val) {
                case '1':
                    return "默认店铺"
                case '2':
                    return "白金店铺"
                default:
                    return '--'
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.store-drawer /deep/ {
    position: absolute;
    height: 100%;
    .el-drawer.rtl {
        overflow: hidden;
        top: 0;
    }
    ::-webkit-scrollbar { 
        width: 9px;
        height: 9px;
    }
    ::-webkit-scrollbar-thumb {
        cursor: pointer;
        background-color: rgba(144, 147, 153, 0.3);
        border-radius: 9px;
    }
    .el-drawer {
        width: 100%;
        max-width: 1280px;
    }
    .el-drawer__header {
        z-index: 10;
        margin-bottom: 16px;
    }
    .el-drawer__body {
        padding: 0 24px 12px;
        display: flex;
        flex-grow: 1;
        height: 0;
        flex-direction: column;
        box-sizing: border-box;
        .search-list {
            flex-grow: 1;
            height: 0;
            .el-table {
                height: 100%!important;
            }
        }
        .search-content {
            padding: 0;
            margin-bottom: 6px;
            .el-form-item {
                margin: 0px 0 10px 0;
                + .el-form-item .el-form-item__label {
                    margin-left: 16px;
                }
                .el-button {
                    margin-left: 12px;
                    + .el-button {
                        margin-left: 8px;
                    }
                }
            }
        }
        .search-list {
            width: 100%;
            .el-table {
                height: 100%;
                .el-table__body-wrapper, .el-table__fixed-body-wrapper {
                    height: calc(100% - 36px)!important;
                    overflow-y: auto;
                }
            }
        }
    }
    .status-0 { color: #999999 }
    .status-1 { color: #67C23A }
    .status-2 { color: #333333 }
    .status-3 { color: #F56C6C }
}
</style>

<style lang="scss">
.el-message-box.qrcode-view {
    width: 400px;
    padding-bottom: 0;
    .el-message-box__content {
        padding: 18px 25px 25px;
        height: 370px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .el-message-box__message { text-align: center; }
    img { 
        max-width: 98%;
    }
}
</style>